package org.vellos.halide.parse;

import java.util.ArrayList;

public class ExpressionNode {

  private ExpressionNode parent;
  private ArrayList<Object> lexicons;

  public ExpressionNode() {
    // Required to get memory pointer before the lexicons have been built.
  }

  public ExpressionNode(ArrayList<Object> lexicons, ExpressionNode parent) {
    this.lexicons = lexicons;
    this.parent = parent;
  }

  public void setLexicons(ArrayList<Object> lexicons) {
    this.lexicons = lexicons;
  }

  public void setParent(ExpressionNode parent) {
    this.parent = parent;
  }

  public ArrayList<Object> getNodes() {
    return lexicons;
  }

  public ExpressionNode getParent() {
    return parent;
  }

  public boolean isLeaf() {
    for (Object o : lexicons) {
      if (o instanceof ExpressionNode) {
        return false;
      }
    }

    return true;
  }

  @Override
  public String toString() {
    String result = "(";

    for (Object o : this.getNodes()) {
      if (o instanceof String) {
        result += o + " ";
      } else if (o instanceof ExpressionNode) {
        result += recurseToString((ExpressionNode) o) + " ";
      } else {
        result += "BAD_NULL ";
      }
    }

    result = result.substring(0, result.length()) + ")";
    return result;
  }

  private String recurseToString(ExpressionNode node) {
    String result = "(";

    for (Object o : node.getNodes()) {
      if (o instanceof String) {
        result += o + " ";
      } else if (o instanceof ExpressionNode) {
        result += recurseToString((ExpressionNode) o) + " ";
      } else {
        result += "BAD_NULL ";
      }
    }

    result = result.substring(0, result.length()) + ")";
    return result;
  }
}
